<template>
  <view class="activity-detail-page" :style="activityStyleBg">
    <view
      class="activity-detail-title"
      :class="{ 'bg-white': bgWhite }"
      :style="activityTitleStyle"
    >
      <view
        class="back-btn"
        :style="{
          'background-image': `url(${activity_back})`,
          height: `${gasbagHeight}px`
        }"
        @tap="goBack"
      />习惯百日行
    </view>
    <!-- <scroll-view
      class="content-scroll"
      :scroll-y="true"
      :lower-threshold="100"
      :style="contentStyle"
    > -->
    <view v-if="activityExists">
      <view class="clock-in-progress">
        <view class="title">
          <view class="title-left">
            打卡进度
          </view>
          <view class="title-right"> {{ clock_num }}/{{ theme_num }} </view>
        </view>
        <special-progress class="progress" :progress="progress" />
      </view>
      <view class="operation-wrap">
        <view class="btn-wrap">
          <borderBox
            v-if="activity_type === TIME_CLOCK"
            class="bx-32"
            :bd-radius="4"
            :inside-padding="4"
            bd-color="#A13D0F"
            bg-color="#FFEEA9"
          >
            <view class="operation-btn" @tap="goCalendar">
              <image :lazy-load="true" :src="calendar_icon" />
              <view class="btn-text">
                打卡日历
              </view>
            </view>
          </borderBox>
          <borderBox
            class="bx-32"
            :bd-radius="4"
            :inside-padding="4"
            bd-color="#A13D0F"
            bg-color="#FFEEA9"
          >
            <view class="operation-btn" @tap="handleInvite">
              <image :lazy-load="true" :src="share_icon" />
              <view class="btn-text">
                邀请
              </view>
            </view>
          </borderBox>
        </view>
        <view class="strategy-btn" @tap="goStrategy">
          <text>攻略</text>
          <image :lazy-load="true" :src="strategy_btn_right" />
        </view>
      </view>
      <view class="activity-detail">
        <borderBox :inside-padding="16" bd-color="#A13D0F" bg-color="#FFFBEA">
          <view class="activity-title text-row-2">
            {{ activity_title }}
          </view>
          <view class="activity-ranking">
            <view class="avatar-wrap">
              <avatar-group
                :avatar="avatar"
                :height="52"
                :avatar-limit-len="7"
              />
            </view>
            <view v-if="activity_status === OVER" class="mid-text">
              <view class="num"> {{ all_clock_num }} </view>人已参与
            </view>
            <view v-else class="mid-text">
              今日已打卡<view class="num">{{ all_clock_num }}</view
              >人
            </view>
            <view
              v-if="activity_status !== OVER"
              class="view-ranking"
              :style="{ 'background-image': `url(${view_ranking_right})` }"
              @tap="goRanking"
            >
              查看排行
            </view>
          </view>
          <view class="activity-btn-wrap">
            <view v-if="is_group_clock" class="group-btn-wrap">
              <view
                class="group-btn"
                :class="{ dis: clockBtnStatus.dis }"
                :style="{ 'background-image': `url(${orange_btn})` }"
                @tap="clockBtnStatus.action()"
              >
                {{ clockBtnStatus.text }}
              </view>
              <view
                class="group-btn has-more"
                :style="{ 'background-image': `url(${red_btn})` }"
                @tap="goGroupDetail"
              >
                {{ group_status ? "查看团" : "组个团" }}
                <view
                  v-if="!group_status"
                  class="more-tips"
                  :style="{ 'background-image': `url(${more_tips_btn})` }"
                >
                  更多奖励
                </view>
              </view>
            </view>
            <view
              v-else
              class="single-btn"
              :class="{ dis: clockBtnStatus.dis }"
              :style="{ 'background-image': `url(${orange_big_btn})` }"
              @tap="clockBtnStatus.action()"
            >
              {{ clockBtnStatus.text }}
            </view>
          </view>
        </borderBox>
      </view>
      <view class="theme-content">
        <view
          class="theme-content-title"
          :style="{ 'background-image': `url(${activity_title_bg})` }"
        >
          主题
        </view>
        <borderBox :inside-padding="16" bd-color="#FFF5D5" bg-color="#FFF5D5">
          <view class="theme-query">
            <view
              class="theme-query-search"
              :style="{ 'background-image': `url(${theme_search})` }"
            >
              <input
                v-model="keywords"
                class="search-input"
                type="text"
                @Confirm="hanleSearch"
                @blur="handleSearchInpBlur"
              />
            </view>
            <view
              class="theme-query-sort"
              :style="{ 'background-image': `url(${theme_sort})` }"
              @tap="handleSort"
            >
              {{ order ? "正序" : "倒序" }}
            </view>
          </view>
          <border-box
            v-for="item in themeList"
            :key="item.id"
            :inside-padding="16"
            bd-color="#CB9064"
            bg-color="#FFFBEA"
            class="border-box-use"
          >
            <view class="theme-item" @tap="goTheme(item.id)">
              <view class="item-left">
                <view class="title" :class="{ clocked: item.status }">
                  {{ item.theme_title }}
                </view>
                <view
                  v-if="activity_type === TIME_CLOCK"
                  class="desc"
                  :style="{ 'background-image': `url(${theme_item_user})` }"
                >
                  {{ `${item.clock_num}人已打卡 | ${item.show_date}` }}
                </view>
                <view
                  v-else
                  class="desc"
                  :style="{ 'background-image': `url(${theme_item_user})` }"
                >
                  {{ `${item.clock_num}人已打卡 | 第${item.checkpoint_num}关` }}
                </view>
              </view>
              <view class="item-right">
                <image :lazy-load="true" :src="item.theme_img" />
              </view>
            </view>
          </border-box>
          <!-- 主题缺省页 -->
          <view v-if="!themeList.length">
            <view
              class="today-empty"
              :style="{ 'background-image': `url(${activity_offline})` }"
            >
              暂无主题～
            </view>
          </view>
        </borderBox>
      </view>
    </view>
    <view v-else class="empty">
      <border-box
        :inside-padding="16"
        bd-color="#CB9064"
        bg-color="#FFFBEA"
        class="empty-wrap-box"
      >
        <view class="empty-wrap">
          <image :lazy-load="true" class="empty-pic" :src="emptyPageInfo.pic" />
          <view class="main">
            {{ emptyPageInfo.tips }}
          </view>
          <view class="tips">
            去首页看看其他活动吧
          </view>
          <view
            class="empty-btn"
            :style="{ 'background-image': `url(${orange_btn})` }"
            @tap="goHomePage"
          >
            立即前往
          </view>
        </view>
      </border-box>
    </view>
    <!-- </scroll-view> -->
    <Invite :invite-data="invite_card" :show.sync="showInvite" />

    <!-- 发放奖励弹窗 -->
    <AwardGive :show.sync="showAward" position="activity_detail" />
  </view>
</template>
<script>
import {
  activity_bg,
  activity_back,
  strategy_btn_right,
  calendar_icon,
  share_icon,
  view_ranking_right,
  orange_btn,
  orange_big_btn,
  red_btn,
  more_tips_btn,
  activity_title_bg,
  theme_item_user,
  theme_search,
  theme_sort,
  not_this_city,
  not_this_grade,
  activity_offline
} from "@/libs/image-url";
import globalData from "@/libs/globalData";
import Taro from "@tarojs/taro";
import specialProgress from "_c/special-progress";
import avatarGroup from "_c/avatar-group";
import borderBox from "_c/border-box/index";
import Invite from "_c/generate-image/invite.vue";
import AwardGive from "@/components/award-give/index.vue";
import { handleJudgeIsLogin, decodeQrcodeScene } from "@/libs/util";
import { activityDetail, themeList, joinActivity } from "_api/activity";

import "./index.scss";

const TIME_CLOCK = 1;
/**
 * 1： 打卡活动上架，并且已到开始打卡日期，用户未参加该打卡活动，按钮展示为：立即加入
2： 用户已参加打卡活动，但今日未打卡，按钮展示为：打卡
3： 用户已参加打卡活动，但今日已打卡，按钮展示为：今日已打卡
4： 打卡活动上架，但未到开始打卡时间，按钮展示为：倒计时X天开始打卡
5： 打卡活动上架，但未到可打卡时间，按钮展示为：非打卡时段
6： 当前时间>活动结束时间，按钮展示：活动已结束
 */
const STARTED = 1;
const NO_CLOCK_IN = 2;
const CLOCKED_IN = 3;
const NOT_DAY = 4;
const NOT_TIME = 5;
const OVER = 6;

/**组团页路径 */
const GROUP_PAGE_ROUTE = "pages/group/home/index";

export default {
  components: {
    Invite,
    specialProgress,
    borderBox,
    avatarGroup,
    AwardGive
  },
  data() {
    return {
      TIME_CLOCK,
      OVER,
      activity_bg,
      strategy_btn_right,
      calendar_icon,
      share_icon,
      view_ranking_right,
      orange_btn,
      orange_big_btn,
      red_btn,
      more_tips_btn,
      activity_title_bg,
      theme_item_user,
      theme_sort,
      theme_search,
      activity_back,
      not_this_city,
      not_this_grade,
      activity_offline,
      NOT_DAY,
      NOT_TIME,
      bgWhite: false,
      showInvite: false,
      showAward: false,
      activity_id: "",
      gasbagHeight: 0,
      gasbagMarTop: 0,
      windowHeight: 0,
      keywords: "",
      activity_type: 1,
      activity_title: "",
      theme_num: 100,
      clock_num: 0,
      invite_title: "",
      invite_background_img: "",
      avatar: [],
      all_clock_num: 0,
      clock_status: 0,
      //组团状态 0未组 1已组
      group_status: 0,
      //活动状态 1存在，2：城市不符，3：年级不符，4：活动不存在；5:活动已结束
      activity_status: 1,
      //活动是否开启组团 1 是 0否
      is_group_clock: 0,
      invite_card: {},
      clock_theme_id: 0,
      countdown: "",
      order: true,
      themeList: [],
      isEnd: false,
      page: 1,
      isLogin: false
    };
  },
  computed: {
    /**背景样式 */
    activityStyleBg() {
      return {
        "background-image": `url("${activity_bg}")`
      };
    },
    activityTitleStyle() {
      return {
        "line-height": `${this.gasbagHeight}px`,
        "padding-top": `${this.gasbagMarTop}px`
      };
    },
    contentStyle() {
      return {
        height: `${this.windowHeight - this.gasbagHeight - this.gasbagMarTop}px`
      };
    },
    activityExists() {
      return this.activity_status === 1 || 6;
    },
    progress() {
      return ((this.clock_num / this.theme_num) * 100).toFixed(2);
    },
    //打卡按钮状态
    clockBtnStatus() {
      switch (this.clock_status) {
        case 1: {
          return {
            text: "立即加入",
            dis: false,
            action: this.addActivity
          };
        }
        case 2: {
          return {
            text: "打卡",
            dis: false,
            action: this.clockIn
          };
        }
        case 3: {
          return {
            text: "今日已打卡",
            dis: true,
            action: null
          };
        }
        case 4: {
          return {
            text: `倒计时${this.countdown}天开始`,
            small: true,
            dis: true,
            action: null
          };
        }
        case 5: {
          return {
            text: "非打卡时段",
            dis: true,
            action: null
          };
        }
        case 6: {
          return {
            text: "打卡已结束",
            dis: true,
            action: null
          };
        }
        case 7: {
          return {
            text: "打卡",
            dis: false,
            action: () => {
              Taro.showToast({
                title: "暂无可打卡主题，请稍后重试",
                icon: "none",
                duration: 2000
              });
            }
          };
        }
        default: {
          return {
            text: "加载中",
            dis: true,
            action: null
          };
        }
      }
    },
    //缺省页
    emptyPageInfo() {
      switch (this.activity_status) {
        case 2: {
          return {
            pic: not_this_city,
            tips: "抱歉，该活动不在您所在的城市"
          };
        }
        case 3: {
          return {
            pic: not_this_grade,
            tips: "抱歉，您所在的年级未参与该活动"
          };
        }
        default: {
          return {
            pic: activity_offline,
            tips: "抱歉，该活动已下架"
          };
        }
      }
    }
  },

  onLoad(opt) {
    const sceneQuery = decodeQrcodeScene(opt?.scene);
    console.log(sceneQuery, opt?.scene, "opt?.scene");
    this.activity_id = sceneQuery?.id || opt.id;
    /**邀请id */
    const invite_id = sceneQuery?.invite_id;
    invite_id && Taro.setStorageSync("login_invite_id", invite_id);

    this.gasbagHeight = globalData.getData("MBHeight");
    this.gasbagMarTop = globalData.getData("MBTop");
    this.windowHeight = globalData.getData("windowHeight");
    /* this.getThemeList(1); */
    this.isLogin = !!Taro.getStorageSync("token");
  },
  onShow() {
    this.showAward = true;
    this.getActivityDetail(this.activity_id);
    /*  &&  */ this.getThemeList(
      1,
      true
    ); /* && ( !this.isLogin && (this.isLogin = true)); */
  },
  // onPullDownRefresh: function() {
  //   // Do something when pull down.
  //   console.log('2323')
  //   setTimeout(()=>{
  //     Taro.stopPullDownRefresh()
  //   },3000)
  // },
  onReachBottom: function() {
    // Do something when page reach bottom.
    if (this.isEnd) {
      return;
    }
    this.getThemeList(this.page);
  },
  onPageScroll: function({ scrollTop }) {
    // Do something when page scroll
    this.bgWhite = scrollTop > 20;
  },
  onShareAppMessage() {
    return {
      title: "hahahahhahaha",
      path: "/pages/activity-detail/index?id=123"
    };
  },
  // onShareTimeline(){
  //   return {
  //     title: 'hahahahhahaha',
  //     query: 'id=123'
  //   }
  // },
  methods: {
    getActivityDetail(id, type = false) {
      activityDetail({ id })
        .then(res => {
          let { id, ...obj } = res.data;
          Object.assign(this.$data, obj);
          type &&
            obj.clock_theme_id &&
            this.clock_status !== 5 &&
            this.clockIn();
        })
        .catch(err => {
          Taro.showToast({
            title: err.message,
            icon: "none",
            duration: 2000
          });
        });
    },
    getThemeList(page, type = false) {
      this.sortLoading = true;
      themeList({
        activity_id: this.activity_id,
        activity_type: this.activity_type,
        keywords: this.keywords,
        order: this.order ? "asc" : "desc",
        page
      })
        .then(({ data }) => {
          type && (this.themeList = []);
          page === 1
            ? (this.themeList = data.data)
            : this.themeList.push(...data.data);
          this.isEnd =
            data.meta.pagination.current_page >=
            data.meta.pagination.total_pages;
          !this.isEnd && (this.page = data.meta.pagination.current_page + 1);
          this.sortLoading = false;
        })
        .catch(err => {
          Taro.showToast({
            title: err.message,
            icon: "none",
            duration: 2000
          });
          this.sortLoading = false;
        });
      /* .finally(()=>{
          this.sortLoading = false
        }) */
    },
    goHomePage() {
      Taro.switchTab({
        url: "/pages/index/index"
      });
    },
    goRanking() {
      Taro.navigateTo({
        url: `/pages/activity-ranking/index?id=${this.activity_id}`
      });
    },
    /**搜索框失焦 */
    handleSearchInpBlur() {
      if (!this.keywords) this.getThemeList(1);
    },
    hanleSearch() {
      /* this.themeList = []; */
      this.getThemeList(1);
    },
    goBack() {
      if (Taro.getCurrentPages().length < 2) {
        Taro.switchTab({
          url: "/pages/index/index"
        });
        return;
      }
      Taro.navigateBack({
        delta: 1
      });
    },
    goStrategy() {
      Taro.navigateTo({
        url: `/pages/strategy/index?id=${this.activity_id}`
      });
    },
    goCalendar() {
      if (handleJudgeIsLogin()) {
        Taro.navigateTo({
          url: `/pages/clock-calendar/index?id=${this.activity_id}`
        });
      }
    },
    goTheme(id) {
      if (!Taro.getStorageSync("token")) {
        Taro.navigateTo({ url: "/pages/not-login/index" });
        return;
      }
      Taro.navigateTo({
        url: `/pages/theme-detail/index?id=${id}`
      });
    },
    addActivity() {
      const hasAuth = handleJudgeIsLogin();
      if (!hasAuth) return;
      joinActivity({ id: this.activity_id })
        .then(r => {
          Taro.showToast({
            title: "加入成功",
            icon: "none",
            duration: 2000
          });
          this.getActivityDetail(this.activity_id, true);
        })
        .catch(err => {
          Taro.showToast({
            title: err.message,
            icon: "none",
            duration: 2000
          });
          if (err.status_code === 4011) {
            this.getActivityDetail(this.activity_id);
          }
        });
    },
    clockIn() {
      Taro.navigateTo({
        url: `/pages/theme-detail/index?id=${this.clock_theme_id}`
      });
    },
    /**跳转组团 */
    goGroupDetail() {
      const pages = Taro.getCurrentPages();
      const groupPageIdx = pages.findIndex(i => i.route === GROUP_PAGE_ROUTE);
      /**没有组团详情 */
      if (groupPageIdx === -1) {
        Taro.navigateTo({
          url: `/pages/group/home/index?id=${this.activity_id}`
        });
        return;
      }
      // 已经包含了组团详情
      const delta = pages.length - groupPageIdx - 1;
      Taro.navigateBack({ delta });
    },
    handleSort() {
      if (this.sortLoading) {
        return;
      }
      this.order = !this.order;
      /* this.themeList = []; */
      this.getThemeList(1);
    },
    handleInvite() {
      const hasAuth = handleJudgeIsLogin();
      if (!hasAuth) return;
      this.showInvite = true;
    }
  }
};
</script>
